package com.dianbo.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import util.AllTypeList;
import util.Constant;

import com.BlackPhoneModule.bean.BlackPhoneBean;
import com.BlackPhoneModule.dao.BlackPhoneModuleDao;
import com.UserModule.bean.TbUserBean;
import com.dati.bean.DatiType;
import com.dianbo.bean.Dianbo;
import com.dianbo.bean.DianboType;
import com.dianbo.dao.DianboDao;
import com.dianbo.dao.DianboTypeDao;
import com.ibm.db2.jcc.b.di;
import com.jifen.bean.JiFen;
import com.jifen.dao.JifenDao;
import com.jspsmart.upload.SmartUpload;

public class DianboServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public DianboServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String method=request.getParameter("method");
		TbUserBean user = (TbUserBean)request.getSession().getAttribute("User");
		if(method.equals("set")){//对点播类型进行积分设置
			String dianboId = request.getParameter("dianboId");
			String condition=" typeId = '"+dianboId+"'";
			List<DianboType> dianboTypeList = new DianboTypeDao().getDianboList("tb_qsType_answer",condition,"createTime");
			for(DianboType dt:dianboTypeList){
				System.out.println("名称"+dt.getTypeName());
			}
			request.getSession().setAttribute("dianboTypeList", dianboTypeList);
			response.sendRedirect("jifen/jiFenupLoadSet.jsp");
		}else if(method.equals("setSubmit")){
			String num = request.getParameter("num");
			String typeId = request.getParameter("typeId");
		
			JiFen jiFen = new JiFen();
			jiFen.setTypeId(typeId);
			jiFen.setIntegralType(0);
			jiFen.setIntegralValue(num);
			jiFen.setSeriseId("");
			jiFen.setSetTime(Constant.decodeDate());
			jiFen.setUserId(user.getUserId());
			boolean bo = new JifenDao().addJiFen(jiFen);
			if(bo){
				request.getSession().setAttribute("result", "积分设置成功");
			}else {
				request.getSession().setAttribute("result", "积分设置失败");
			}
			List list = new AllTypeList().getLastValue(user.getUserId());
			List<DianboType> dianboTypeList = (ArrayList<DianboType>)list.get(0);
			StringBuffer sb = (StringBuffer)list.get(1);
		   
		    request.getSession().setAttribute("dianboTypeList", dianboTypeList);
		    request.getSession().setAttribute("sb", sb);
		    response.sendRedirect("jifen/jiFenupLoadList.jsp");
		}else if(method.equals("setDown")){
			String dianboId = request.getParameter("dianboId");
			String condition=" typeId = '"+dianboId+"'";
			List<DianboType> dianboTypeList = new DianboTypeDao().getDianboList("tb_qsType_answer",condition,"createTime");
			request.getSession().setAttribute("dianboTypeList", dianboTypeList);
			response.sendRedirect("jifen/jiFendownSet.jsp");
		}else if(method.equals("setDownSubmit")){//设置点播的下行积分提交
			String num = request.getParameter("num");
			String typeId = request.getParameter("typeId");
		
			JiFen jiFen = new JiFen();
			jiFen.setTypeId(typeId);
			jiFen.setIntegralType(1);
			jiFen.setIntegralValue(num);
			jiFen.setSeriseId("");
			jiFen.setSetTime(Constant.decodeDate());
			jiFen.setUserId(user.getUserId());
			boolean bo = new JifenDao().addJiFen(jiFen);
			if(bo){
				request.getSession().setAttribute("result", "点播下行积分设置成功");
			}else {
				request.getSession().setAttribute("result", "点播下行积分设置失败");
			}
			
			List list = new AllTypeList().getDownValue(user.getUserId());
			List<DianboType> dianboTypeList = (ArrayList<DianboType>)list.get(0);
			List<DatiType> datiTypeList = (ArrayList<DatiType>)list.get(1);
		    request.getSession().setAttribute("result", "");
		    request.getSession().setAttribute("dianboTypeList", dianboTypeList);
		    request.getSession().setAttribute("datiTypeList", datiTypeList);
		    response.sendRedirect("jifen/jiFendownList.jsp");
		}else if(method.equals("lookdianbo")){
			//查询所有点播资源库的信息
			String content=request.getParameter("content");
			content=Constant.decodeString(content); 
			List dianboList=new DianboDao().getDianboList("tb_qs_info","qsUpTime", "");
			request.getSession().setAttribute("selectdianbotype", "");
			request.getSession().setAttribute("dianboList", dianboList);
			request.getSession().setAttribute("content", content);
			response.sendRedirect("hudong/dianboList.jsp?s=1");
			
		}else if(method.equals("looksearch")){
			String content=request.getParameter("content");
			content=Constant.decodeString(content); 
			String dianbotype=request.getParameter("dianbotype");
			String tiaojian=" 1=1";
			if(content==null || "".equals(content)){
				content="";
				
			}else{
				tiaojian+=" and  qsContent like '%"+content+"%'";
			}
			System.out.println("dianbotype:"+dianbotype);
			if("0".equals(dianbotype)){
				
			}else{
				tiaojian+=" and typeId="+dianbotype;
			}
			
			List dianboList=new DianboDao().getDianboList("tb_qs_info","qsUpTime", tiaojian);
			request.getSession().setAttribute("selectdianbotype", dianbotype);	
			request.getSession().setAttribute("dianboList", dianboList);
			request.getSession().setAttribute("content", content);
			response.sendRedirect("hudong/dianboList.jsp?s=1");
		
	}else if(method.equals("deleteOne")){
		String qsInfoId=request.getParameter("qsInfoId");
		boolean result=new DianboDao().del("tb_qs_info", "qsInfoId", qsInfoId);
		if(result){
			request.getSession().setAttribute("resultSM", "此点播记录删除成功！");
		}else{
			request.getSession().setAttribute("resultSM", "此点播记录删除失败！");
		}
		String content=request.getParameter("content");
		content=Constant.decodeString(content); 
		String dianbotype=request.getParameter("dianbotype");
		List dianboList=new DianboDao().getDianboList("tb_qs_info","qsUpTime", "");
		request.getSession().setAttribute("selectdianbotype", dianbotype);
		request.getSession().setAttribute("dianboList", dianboList);
		request.getSession().setAttribute("content", content);
		response.sendRedirect("hudong/dianboList.jsp?s=1");
	}else if(method.equals("deleteAll")){
		String idList = request.getParameter("idList");
		idList = idList.substring(0, idList.length()-1);
		boolean result=new DianboDao().delin("tb_qs_info", "qsInfoId", idList);
		if(result){
			request.getSession().setAttribute("resultSM", "点播记录删除成功！");
		}else{
			request.getSession().setAttribute("resultSM", "点播记录删除失败！");
		}
		String content=request.getParameter("content");
		content=Constant.decodeString(content); 
		String dianbotype=request.getParameter("dianbotype");
		List dianboList=new DianboDao().getDianboList("tb_qs_info","qsUpTime", "");
		request.getSession().setAttribute("selectdianbotype", dianbotype);
		request.getSession().setAttribute("dianboList", dianboList);
		request.getSession().setAttribute("content", content);
		response.sendRedirect("hudong/dianboList.jsp?s=1");
	}else if(method.equals("importDianboSubmit")){
		
		String realImagePath = Constant.decodeString(request
				.getParameter("realImagePath"));
		String tempPath = request.getRealPath("/")
				+ "upload".replace("\\", "/");
		String result = "";
		File file = new File(tempPath);
		if(!file.isFile()){
			file.mkdirs();
		}
		// new a SmartUpload object
		SmartUpload su = new SmartUpload();
		su.setCharset("UTF-8");// 使用时候最关键的一步
		// 上传初始化
		su.initialize(this.getServletConfig(),request,response);

		// 设定上传限制
		// 1.限制每个上传文件的最大长度。
		su.setMaxFileSize(10000000);
		// 2.限制总上传数据的长度。
		su.setTotalMaxFileSize(20000000);
		// 3.设定允许上传的文件（通过扩展名限制）,仅允许doc,txt文件。
		su.setAllowedFilesList("xls,XLS");
		boolean sign = true;
		// 4.设定禁止上传的文件（通过扩展名限制）,禁止上传带有exe,bat,jsp,htm,html扩展名的文件和没有扩展名的文件。
		try {
			su.setDeniedFilesList("exe,bat,jsp,htm,html");
			// 上传文件
			su.upload();
			// 将上传文件保存到指定目录
			tempPath = tempPath.replace("\\", "/");
			tempPath = tempPath + "/";
			
			su.save(tempPath);
			System.out.println("文件名称"+su.getFiles().getFile(0).getFileName());
			tempPath += "\\" + su.getFiles().getFile(0).getFileName();
			tempPath = tempPath.replace("\\", "/");
			tempPath = tempPath.replace("//", "/");
			System.out.println("tempsssssssssssssPath==="+tempPath);
			
			
			Workbook wb;
			InputStream is2 = new FileInputStream(tempPath);
			wb = Workbook.getWorkbook(is2);
			Sheet sheet = wb.getSheet(0);
			int row = sheet.getRows();
			List<Dianbo> DianboList = new ArrayList<Dianbo>();
			//// 表结构是：手机号码，当前时间
			for(int i = 1;i<row;i++){
				Cell firstCell = sheet.getCell(0, i);
				String firstContent = firstCell.getContents();
				Cell secondCell = sheet.getCell(1, i);
				String secondContent = secondCell.getContents();
				if(firstContent.equals("")&&secondContent.equals("")){
					break;
				}
				Dianbo dianboBean=new Dianbo();
				boolean iscunzaitype=new DianboTypeDao().getTypeByName(firstContent);
				//判断是否存在此点播类型
				String Typeid="";
				if(iscunzaitype){
					DianboType dianboType=new DianboTypeDao().getDianboTypebyName(firstContent);
					Typeid=dianboType.getTypeId();
				}else{//不存在此点播类型时，创建类型，并获取其类型id
					DianboType dianboType=new DianboType();
					dianboType.setTypeName(firstContent);
					dianboType.setUserId(user.getUserId());
					dianboType.setCreateTime(Constant.decodeDate());
					Typeid=Constant.getNum();
					dianboType.setTypeId(Typeid);
					boolean addtype=new DianboTypeDao().addDianboType(dianboType);
					//Typeid=new DianboTypeDao().getMaxtypeid();
					
				}
				dianboBean.setQsContent(secondContent);
				dianboBean.setTypeId(Typeid);
				dianboBean.setQsUpTime(Constant.decodeDate());
				dianboBean.setQsUpPhone("");
				DianboList.add(dianboBean);
			}
			
			if(DianboList!=null&&DianboList.size()>0){
				boolean bo = new DianboDao().saveDianboList(DianboList);
				if(bo){
					result="点播记录导入成功";
				}else{
					result="点播记录导入失败";
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		List  BlackPhoneList=null;
		request.getSession().setAttribute("selectdianbotype", "");
		request.getSession().setAttribute("resultSM", result);
		//String content=request.getParameter("content");
		List dianboList=new DianboDao().getDianboList("tb_qs_info","qsUpTime", "");
		
		request.getSession().setAttribute("dianboList", dianboList);
		request.getSession().setAttribute("content", "");
		response.sendRedirect("hudong/dianboList.jsp?s=1");
		
	}else if(method.equals("addDianboSubmit")){
		String typeid=request.getParameter("dianbotypeadd");
		String qsContent=request.getParameter("Dianbocontent");
		Dianbo dianboBean=new Dianbo();
		dianboBean.setTypeId(typeid);
		dianboBean.setQsContent(qsContent);
		dianboBean.setQsUpTime(Constant.decodeDate());
		dianboBean.setQsUpPhone("");
		String result="";
		boolean bo = new DianboDao().addDianbo(dianboBean);
		if(bo){
			result="点播记录新增成功";
		}else{
			result="点播记录新增失败";
		}
		
		request.getSession().setAttribute("selectdianbotype", "");
		request.getSession().setAttribute("resultSM", result);
		List dianboList=new DianboDao().getDianboList("tb_qs_info","qsUpTime", "");
		request.getSession().setAttribute("dianboList", dianboList);
		request.getSession().setAttribute("content", "");
		response.sendRedirect("hudong/dianboList.jsp?s=1");
	}
	}

	public List<DianboType> getDianboType(TbUserBean user){
		String condition="userId = "+user.getUserId();
	    List<DianboType> dianboTypeList = new ArrayList<DianboType>();
	    dianboTypeList = new DianboTypeDao().getDianboList("tb_qsType_answer", condition, "createTime");
	    return dianboTypeList;
	}
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		doGet(request,response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	/**
	 *@author qingyu zhang
	 *@function:
	 *2011-4-4
	 *下午02:40:37
	 *zzClub
	 *com.dianbo.servlet
	 */
}
